package nl.windgazer.arachne.services;

import org.apache.tapestry5.BaseValidationDecorator;
import org.apache.tapestry5.Field;
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.ValidationTracker;
import org.apache.tapestry5.dom.Element;
import org.apache.tapestry5.services.Environment;

public class SimpleValidationDecorator extends BaseValidationDecorator {

	private Environment environment;
	private MarkupWriter writer;

	public SimpleValidationDecorator(Environment environment,
			MarkupWriter writer) {
		this.environment = environment;
		this.writer = writer;
	}

	@Override
	public void insideLabel(Field field, Element labelElement) {
		final Element parent = labelElement.getContainer();
		labelElement.attribute("id", field.getClientId() + "-label");
		if (inError(field)) {
			ValidationTracker tracker = getTracker(); 
			parent.attribute("title", tracker.getError(field)); 
            parent.addClassName("validation-error");
		}
	}

	@Override
	public void afterField(Field field) {
		if (inError(field)) {
			Element p = writer.element("p", "class", "validation-msg msg" + field.getClientId());
			p.raw(getTracker().getError(field));
			writer.end();
		}
		final Element parent = writer.getElement();
		if (field.isRequired()) {
			parent.addClassName("validation-required");
		}
	}

	private boolean inError(Field field) { 
        ValidationTracker tracker = getTracker(); 
        return tracker.inError(field); 
	}
	private ValidationTracker getTracker() { 
         return environment.peekRequired(ValidationTracker.class); 
	} 
}
